/**
 * $Revision: 1.0 $
 * $Author: Eric Yang $
 * $Date: Apr 2, 2010 11:52:11 PM $
 *
 * Author: Eric Yang
 * Date  : Apr 2, 2010 11:52:11 PM
 *
 */
package com.gooex.web.struts.intercepter;

import java.util.HashMap;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import org.c4j.net.URLTools;
import org.c4j.string.StringTools;

import com.gooex.service.organization.IApplicationSessionContext;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

/**
 * @author Eric Yang
 * @version 1.0
 */
public class URLHistoryIntercepter extends AbstractInterceptor {

	private static final String _URL_FROM = "urlfrom";

	private static final String _URL_TEXT = "urltext";

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		Queue<Map<String, String>> queue = getHistoryURLs();
		try {
			String urlFrom = request.getParameter(_URL_FROM);
			if (StringTools.isNotBlankOrNull(urlFrom)) {
				HashMap<String, String> url = new HashMap<String, String>();
				url.put(IApplicationSessionContext._LINK_ADDR, urlFrom);
				String urlText = request.getParameter(_URL_TEXT);
				if (StringTools.isBlankOrNull(urlText))
					urlText = "返回";
				url.put(IApplicationSessionContext._LINK_TEXT, urlText);
				queue.add(url);
			} else {
				String method = request.getMethod();
				if ("GET".equals(method.toUpperCase())) {
					Map<String, String> top = queue.peek();
					if (top != null) {
						String linkAddr = top.get(IApplicationSessionContext._LINK_ADDR);
						String buildOriginalURL = URLTools.buildOriginalURL(request);
						if (!linkAddr.equals(buildOriginalURL))
							queue.clear();
					}
				}
			}
		} catch (Exception e) {
		}
		return invocation.invoke();
	}

	public final Queue<Map<String, String>> getHistoryURLs() {
		Queue<Map<String, String>> queue = (Queue<Map<String, String>>) ActionContext.getContext().getSession().get(
				IApplicationSessionContext._BACK_URLS);
		if (queue == null) {
			queue = new ConcurrentLinkedQueue<Map<String, String>>();
			ActionContext.getContext().getSession().put(IApplicationSessionContext._BACK_URLS, queue);
		}
		return queue;
	}
}
